<template>
  <div class="container" style="max-width: 100%;">
    <div class="app col-md-12" style="background: #fff; padding:10px ; border-radius: 5px; margin-top:30px ; ">
      <div style="display: flex; justify-content: space-between;">
        <div style="width:60%;">
          <el-dialog title="添加设备" :visible.sync="dialogTableVisible" :show-close="false">
            <el-form :model="params">
              <el-form-item label="设备名称" :label-width="formLabelWidth">
                <el-input v-model="params.detail" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="设备编号" :label-width="formLabelWidth">
                <el-input v-model="params.equipmentNo" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="序列号" :label-width="formLabelWidth">
                <el-input v-model="params.equipmentNo" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="类别" :label-width="formLabelWidth">
                <el-select v-model="params.type" placeholder="选择使用类型">
                  <el-option label="家用" value="1"></el-option>
                  <el-option label="商用" value="2"></el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogTableVisible = false">取 消</el-button>
              <el-button type="primary" @click="adDevice">确 定</el-button>
            </div>
          </el-dialog>
          <el-input placeholder="请输入设备名或设备编号" v-model="devname" style="max-width: 200px;margin-right:20px"></el-input>
          <template>
            <el-select v-show='false' v-model="state" placeholder="设备状态" style="margin-right: 20px;">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </template>
          <template>
            <el-select v-show='false' v-model="category" placeholder="类别" style="margin-right: 20px;">
              <el-option v-for="item in option" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </template>
          <template>
            <el-select v-model="typeValue" placeholder="全部" style="margin-right: 20px;">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </template>
          <el-button @click="queryDev" style="margin-right: 20px;">查询</el-button>
          <el-button @click="emptyDev" style="margin-left: 0;">清空</el-button>
        </div>
        <!-- 添加设备弹窗 -->
        <div style="display: flex;">
          <div>
            <el-tooltip class="item" effect="light" content="批量导入" placement="top-start" style="margin-right: 10px;">
              <i class="el-icon-upload" @click="uploadEqui"
                style="line-height: 32px; font-size:26px ; color:#409EFF;"></i>
            </el-tooltip>
          </div>
          <el-button type="primary" plain @click="dialogTableVisible = true"
            style="padding: 3px;height:32px">添加设备</el-button>
        </div>
      </div>
      <!-- 批量删除 -->
      <div style="margin-top: 5px;">
        <el-button @click="deleteAll" style="margin-left: 0%;padding: 8px 10px;">批量删除</el-button>
      </div>
      <template>
        <el-table @selection-change="handleSelectionChange" :data="tableData" border height="542"
          style="width: 100%; margin-top: 10px;" :index-key="index => index">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="equipmentNo" label="设备编号" width="180"></el-table-column>
          <el-table-column prop="detail" label="中文名称" width="180"></el-table-column>
          <el-table-column prop="addr" label="安装地点" width="180"></el-table-column>
          <el-table-column prop="type" label="设备类型" width="120">
            <template slot-scope="type">
              <span v-show="type.row.type == 1">家用</span>
              <span v-show="type.row.type == 2">商用</span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="设备状态" width="120">
            <template slot-scope="status">
              <span v-show="status.row.status == 0">未启用</span>
              <span v-show="status.row.status == 1">正常</span>
              <span v-show="status.row.status == 2">离线</span>
              <span v-show="status.row.status == 3">故障</span>
              <span v-show="status.row.status == 4">报警</span>
            </template>
          </el-table-column>
          <el-table-column prop="agreement" label="协议" width="120">
            <template slot-scope="agreement">
              <span v-show="agreement.row.agreement == 1">MQTT</span>
              <span v-show="agreement.row.agreement == 2">天汇标准</span>
            </template>
          </el-table-column>
          <el-table-column prop="imei" label="设备识别码" width="180"></el-table-column>
          <el-table-column prop="timeBcd" label="上线时间" width="180"></el-table-column>
          <el-table-column prop="ch4" label="甲烷浓度 (%ELE)" width="180"></el-table-column>
          <el-table-column prop="temperature" label="环境温度 (℃)" width="180"></el-table-column>
          <!-- <el-table-column prop="notes" label="地址" width="180"></el-table-column> -->
          <el-table-column prop="lng" label="经度" width="100"></el-table-column>
          <el-table-column prop="lat" label="纬度" width="100"></el-table-column>
          <el-table-column prop="addrDetail" label="详细地址" width="180"></el-table-column>
          <el-table-column prop="mainBind" label="主绑人" width="180">
            <template slot-scope="scope">
              <!-- <div @click="TMhos(scope.row)">{{ scope.row.mainBind }}</div> -->
              <el-popover placement="right" width="400" trigger="click">
                <el-table :data="gridData">
                  <el-table-column property="data" label="绑定人"></el-table-column>
                  <el-table-column width="50">
                    <template slot-scope="scope">
                      <div @click="deleteTMH(scope.row)">删除</div>
                    </template>
                  </el-table-column>
                </el-table>
                <div @click="TMhos(scope.row)" slot="reference">{{ scope.row.mainBind }}</div>
              </el-popover>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="notes" label="备注" width="180"></el-table-column> -->
          <el-table-column fixed="right" label="操作" width="100">
            <template slot-scope="scope">
              <el-button @click="replaceDev(scope.row)" type="primary" size="small">编辑</el-button>
              <el-button @click.native.prevent="deleteRow(scope, tableData)" type="danger" size="small">
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
          :page-sizes="[10, 15, 20]" :page-size="10" layout="total, sizes, prev, pager, next, jumper" :total="tota">
        </el-pagination>
      </template>
      <pop :params="params" :showHide="showHide" @custom-event="devHidden"></pop>
      <batchUpload :uploadshow="uploadshow" @upload-event="uploadeve"></batchUpload>
      <Delete :deletshow="deletshow" :deleteurl="deleteurl" @delete-event="deleteDialog" :selectList="selectList">
      </Delete>
    </div>
  </div>
</template>
  
<script>
import { AddDevice, GetDevice, DelateDevice, getData, postData } from '@/api/table'
import { Message } from 'element-ui'
import pop from '@/components/public/pop.vue'
import batchUpload from '@/components/Form/Dialog/batchUpload.vue'
// 批量删除弹窗
import Delete from "@/components/Form/delete.vue";

export default {
  // 组件
  components: {
    pop, batchUpload, Delete
  },
  data() {
    return {
      gridData: [],
      //批量删除路径
      deleteurl: '/equipment/batchRemove',
      // 批量上传控制显示
      uploadshow: false,

      // 查询名字字段
      devname: '',

      tableData: [],

      // 默认每页显示的条数（可修改）
      PageSize: 10,

      // 默认显示第一条
      currentPage: 1,

      // 总条数，根据接口获取数据长度(注意：这里不能为空)
      totalCount: 1,

      dialogTableVisible: false,
      // 组件显示隐藏
      showHide: false,

      params: {
        "equipmentNo": "",//设备编号 1
        "detail": "",//中文名称 1
        "addr": "",//安装地点
        "addrDetail": "",//详细地址
        "imei": "", //国际移动设备识别码
        "lat": "",
        "lng": "",
        "mainBind": "",//主绑人
        "notes": "",//备注
        "status": "",//设备状态
        "type": "",//设备类型 1
        "ch4": '',//甲烷浓度
        "temperature": '',//环境温度
        'timeBcd': '',
      },
      formLabelWidth: '120px',
      // 总条数
      tota: 0,
      // 设备状态筛选列表
      options: [{
        value: '',
        label: '全部'
      }, {
        value: '0',
        label: '未启用'
      }, {
        value: '1',
        label: '正常'
      }, {
        value: '2',
        label: '离线'
      }, {
        value: '3',
        label: '故障'
      }, {
        value: '4',
        label: '报警'
      },],
      // 类别
      option: [{
        value: '1',
        label: '家用'
      }, {
        value: '2',
        label: '商用'
      },],
      // 类别
      typeValue: '',
      category: '',
      state: '',
      deletshow: false,
      // 批量删除数组
      selectList: [],
      forData: null
    }
  },

  methods: {
    //主绑人
    TMhos(data) {
      // console.log(data);
      this.gridData = [];
      this.forData = new FormData()
      const url = '/equipment/bindList'
      console.log(data.equipmentNo);

      this.forData.append('equipmentNo', data.equipmentNo)
      getData(url, 'post', this.forData).then(res => {
        if (res.msg.length !== 0) {
          for (let index = 0; index < res.msg.length; index++) {
            if (data.mainBind == res.msg[index]) {
              this.gridData.push({ 'data': '主绑人 : ' + res.msg[index], 'equipmentNo': data.equipmentNo, 'id': res.msg[index] })
            } else {
              this.gridData.push({ 'data': '绑定人 : ' + res.msg[index], 'equipmentNo': data.equipmentNo, 'id': res.msg[index] })
            }
          }
        }
      })
    },
    // 删除次级绑定人
    deleteTMH(data) {
      console.log(data);
      let URL = '/equipment/relieve'
      this.forData = new FormData()
      this.forData.append('equipmentNo', data.equipmentNo)
      this.forData.append('userId', data.id)
      getData(URL, 'post', this.forData).then(res => {
        Message({
          message: res.msg,
          type: 'success',
          duration: 3 * 1000
        })
        if (res.code == 0) {
          this.gridData = [];
          const url = '/equipment/bindList'
          this.forData = new FormData()
          this.forData.append('equipmentNo', data.equipmentNo)
          getData(url, 'post', this.forData).then(res => {
            if (res.msg.length !== 0) {
              for (let index = 0; index < res.msg.length; index++) {
                if (data.mainBind == res.msg[index]) {
                  this.gridData.push({ 'data': '主绑人 : ' + res.msg[index], 'equipmentNo': data.equipmentNo, 'id': res.msg[index] })
                } else {
                  this.gridData.push({ 'data': '绑定人 : ' + res.msg[index], 'equipmentNo': data.equipmentNo, 'id': res.msg[index] })
                }
              }
            }
          })
        }
      })
    },
    //批量删除对话框返回对话框是否显示
    deleteDialog(data) {
      this.deletshow = data
    },
    //批量删除选中
    handleSelectionChange(val) {
      // console.log(val);
      let setlist = []
      for (let index = 0; index < val.length; index++) {
        setlist.push(val[index].id)
        setlist.filter(item => { return item })
      }
      // 批量删除数组
      this.selectList = setlist
      // console.log(this.selectList);
    },
    //批量删除
    deleteAll() {
      if (this.selectList.length == 0) {
        Message({
          message: '选择不能为空',
          type: 'waring',
          duration: 3 * 1000
        })
      } else {
        this.deletshow = true
      }
    },
    //批量导入
    uploadEqui() {
      this.uploadshow = true
    },
    // 删除设备
    deleteRow(scops, rows) {
      let data = { equipmentId: scops.row.id }
      DelateDevice(data).then(res => {
        if (res.code == 0) {
          rows.splice(scops.$index, 1);
        }
        let data = { limit: this.PageSize, offset: this.PageSize * (this.currentPage - 1), search: this.devname }
        GetDevice(data).then(res => {
          this.tableData = res.msg
          this.tota = res.total
        })
      })
    },
    // 查询表单条数
    handleSizeChange(val) {
      this.PageSize = val
      let data = { limit: val, offset: this.currentPage - 1, search: this.devname, status: this.typeValue }
      GetDevice(data).then(res => {
        this.tableData = res.msg
      })
    },
    // 查询表单页数
    handleCurrentChange(val) {
      this.currentPage = val
      let data = { limit: this.PageSize, offset: this.PageSize * (this.currentPage - 1), search: this.devname, status: this.typeValue }
      GetDevice(data).then(res => {
        this.tableData = res.msg
      })
    },
    // 添加设备列表
    adDevice() {
      // 关闭弹窗
      this.dialogTableVisible = false
      let param = JSON.stringify(this.params)
      let data = { params: param }
      AddDevice(data).then(res => {
        GetDevice().then(res => {
          this.tableData = res.msg
          this.tota = res.total
        })
        Message({
          message: res.msg,
          type: 'success',
          duration: 3 * 1000
        })
      })
      this.params = {
        "addr": "",
        "addrDetail": "",
        "detail": "",
        "equipmentNo": "",
        "imei": "",
        "lat": "",
        "lng": "",
        "mainBind": "",
        "notes": "",
        "status": "",
        "type": ""
      }
    },
    //修改设备
    replaceDev(prop) {
      this.showHide = true;
      this.params = prop
    },
    // 组件穿过来对话框是否显示
    devHidden(data) {
      this.showHide = data
      this.params = {
        "addr": "",
        "addrDetail": "",
        "detail": "",
        "equipmentNo": "",
        "imei": "",
        "lat": "",
        "lng": "",
        "mainBind": "",
        "notes": "",
        "status": "",
        "type": ""
      }
    },
    uploadeve(data) {
      this.uploadshow = data
    },
    //查询设备
    queryDev() {
      // this.devname; 输入框输入的内容
      this.pageSize = 10
      this.currentPage = 1
      let data = { search: this.devname, status: this.typeValue }
      GetDevice(data).then(res => {
        this.tableData = res.msg
        this.tota = res.total
      })
    },
    // 清空查询
    emptyDev() {
      this.typeValue = ''
      this.state = ''
      this.category = ''
      this.devname = ''
      GetDevice().then(res => {
        this.tableData = res.msg
        this.tota = res.total
      })
    }
  },
  created() {
    // console.log(this.$route.params.id);
    this.typeValue = this.$route.params.id
    let data = { status: this.typeValue }
    // 获取设备列表
    GetDevice(data).then(res => {
      // console.log(res);
      this.tableData = res.msg
      this.tota = res.total
    })
  },

}
</script>
<style>
.el-table .cell {
  height: 24px;
  white-space: nowrap;
}

.el-table td.el-table__cell div {
  height: 24px;
  white-space: nowrap;
}

.el-table .el-table__cell {
  padding: 11px 0;
}

.el-button--small {
  padding: 3px;
}

.el-table--fit {
  border: 1px solid #e2e2e2;
}

@media (min-width: 1200px) {

  .container-xl,
  .container-lg,
  .container-md,
  .container-sm,
  .container {
    max-width: 1320px;
  }
}

input:focus {
  border-bottom: 1px solid #007bff;
  outline: 1px solid #007bff;
  /*border-color: #007bff; 移除默认的蓝色轮廓线 */
}

.el-dialog {
  width: 50% !important;
}

.el-table td.el-table__cell,
.el-table th.el-table__cell.is-leaf {
  border: 1px solid #EBEEF5;
}
</style>
  